package com.gxuwz.stats.controller.twoAdmin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.CreativeAchievement;
import com.gxuwz.stats.entity.IntellectualProperty;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.IntellectualPropertyService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/twoIntellectualPro")
public class IntellectualProTwoController {
    @Autowired
    private IntellectualPropertyService intellectualPropertyService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getTwoAdminIntelProList")
    public ResponseEntity<Map<String, Object>> getTwoAdminIntelProList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            System.out.println("params="+params);
            // 提取 Token 并解析用户信息
            String token = authorization.replace("Bearer ", "");

//            int userId = jwtTokenUtil.getUserIdFromToken(token);
            String department = jwtTokenUtil.getDepartmentFromToken(token); // 获取部门信息

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<IntellectualProperty> page = new Page<>(currentPage, pageSize);
//            QueryWrapper<IntellectualProperty> queryWrapper = new QueryWrapper<>();

//// 添加部门过滤条件
//            if (StringUtils.isNotBlank(department)) {
//                queryWrapper.eq("u.department", department);
//            }
//
//            // 增加姓名搜索条件
//            if (params.containsKey("username") && StringUtils.isNotBlank(params.get("username"))) {
//                queryWrapper.and(wrapper -> wrapper.like("u.username", params.get("username")));
//            }
//
//            // 模糊查询条件 - 成果名称
//            if (params.containsKey("intellectualAchievementName") && StringUtils.isNotBlank(params.get("intellectualAchievementName"))) {
//                queryWrapper.like("intellectual_achievement_name", params.get("intellectualAchievementName"));
//            }
//
//            // 模糊查询条件 - 授权号
//            if (params.containsKey("authorizationNumber") && StringUtils.isNotBlank(params.get("authorizationNumber"))) {
//                queryWrapper.like("authorization_number", params.get("authorizationNumber"));
//            }
//
//            // 模糊查询条件 - 成果类别
//            if (params.containsKey("intellectualCategory") && StringUtils.isNotBlank(params.get("intellectualCategory"))) {
//                queryWrapper.like("intellectual_category", params.get("intellectualCategory"));
//            }

            // 调用 service 层的分页查询方法
            IPage<IntellectualProperty> resultPage = intellectualPropertyService.selectCustomPage(page,  department,
                    params.get("username"),
                    params.get("nameKeyword"),
                    params.get("numberKeyword"),
                    params.get("intellectualCategory"));

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addTwoAdminIntelPro")
    public ResponseEntity<Map<String, Object>> saveIntellectualPro(@RequestBody IntellectualProperty intellectualProperty,
                                                                   @RequestHeader("Authorization") String authorization) {
        System.out.println("前端数据：" + intellectualProperty);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = intellectualProperty.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
//        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        intellectualProperty.setUserId(userId);

        // 将用户ID列表转换为逗号分隔的字符串
//        String userIdsStr = userIds.stream().map(String::valueOf).collect(Collectors.joining(","));
//        System.out.println("userIdsStr = "+userIdsStr);
        // 设置到实体类中
//        intellectualProperty.setUserId(userIdsStr);
        // 1. 自动计算分值
        int baseScore = intellectualPropertyService.getScoreByType(intellectualProperty.getIntellectualCategory());
        intellectualProperty.setIntellectualScore(baseScore);

        // 2. 计算总分值
//        intellectualPropertyService.calculateTotalScore(intellectualProperty);

        try {
//            System.out.println("intellectualProperty="+intellectualProperty);
            // 保存到数据库
            intellectualPropertyService.save(intellectualProperty);
            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/updateTwoAdminIntelPro")
    public ResponseEntity<Map<String, Object>> updateIntellectualPro(
            @RequestBody IntellectualProperty intellectualProperty
    ) {
        // 1. 获取前端传递的用户名
        String username = intellectualProperty.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            intellectualProperty.setUserId(user.getUserId());
        }

        // 1. 自动计算分值
        int baseScore = intellectualPropertyService.getScoreByType(intellectualProperty.getIntellectualCategory());
        intellectualProperty.setIntellectualScore(baseScore);

        // 2. 计算总分值
//        intellectualPropertyService.calculateTotalScore(intellectualProperty);

        intellectualPropertyService.updateById(intellectualProperty);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/deleteTwoAdminIntelPro")
    public ResponseEntity<Map<String, Object>> deleteTwoAdminIntelPro(@RequestBody List<Long> ids) {
        intellectualPropertyService.removeByIds(ids);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

}
